package com.ruyuan.eshop.order.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruyuan.eshop.common.constants.RocketMqConstant;
import com.ruyuan.eshop.common.core.JsonResult;
import com.ruyuan.eshop.common.enums.CustomerAuditResult;
import com.ruyuan.eshop.common.enums.CustomerAuditSourceEnum;
import com.ruyuan.eshop.common.message.ActualRefundMessage;
import com.ruyuan.eshop.common.redis.RedisLock;
import com.ruyuan.eshop.customer.api.CustomerApi;
import com.ruyuan.eshop.customer.domain.request.CustomerReviewReturnGoodsRequest;
import com.ruyuan.eshop.fulfill.api.FulfillApi;
import com.ruyuan.eshop.order.api.AfterSaleApi;
import com.ruyuan.eshop.order.dao.*;
import com.ruyuan.eshop.order.domain.dto.LackDTO;
import com.ruyuan.eshop.order.domain.entity.AfterSaleInfoDO;
import com.ruyuan.eshop.order.domain.entity.AfterSaleItemDO;
import com.ruyuan.eshop.order.domain.entity.AfterSaleLogDO;
import com.ruyuan.eshop.order.domain.request.*;
import com.ruyuan.eshop.order.enums.AfterSaleStatusChangeEnum;
import com.ruyuan.eshop.order.enums.AfterSaleStatusEnum;
import com.ruyuan.eshop.order.exception.OrderBizException;
import com.ruyuan.eshop.order.exception.OrderErrorCodeEnum;
import com.ruyuan.eshop.order.manager.OrderNoManager;
import com.ruyuan.eshop.order.mq.producer.DefaultProducer;
import com.ruyuan.eshop.order.service.OrderAfterSaleService;
import com.ruyuan.eshop.order.service.impl.AfterSaleOperateLogFactory;
import com.ruyuan.eshop.pay.api.PayApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @author lxg
 * @Description:訂單中心-逆向售後接口
 * @date 2022/4/1521:57
 */
@Slf4j
@DubboService(version = "1.0.0", interfaceClass = AfterSaleApi.class, retries = 0)
public class AfterSaleApiImpl implements AfterSaleApi {

    @Autowired
    private OrderPaymentDetailDAO orderPaymentDetailDAO;

    @Autowired
    private RedisLock redisLock;

    @DubboReference(version = "1.0.0")
    private PayApi payApi;

    @DubboReference(version = "1.0.0")
    private FulfillApi fulfillApi;

    @Autowired
    private OrderInfoDAO orderInfoDAO;

    @Autowired
    private OrderOperateLogDAO orderOperateLogDAO;

    @Autowired
    private OrderNoManager orderNoManager;

    @Autowired
    private AfterSaleInfoDAO afterSaleInfoDAO;

    @DubboReference(version = "1.0.0")
    private CustomerApi customerApi;

    @Autowired
    private OrderItemDAO orderItemDAO;

    @Autowired
    private AfterSaleLogDAO afterSaleLogDAO;

    @Autowired
    private AfterSaleRefundDAO afterSaleRefundDAO;

    @Autowired
    private DefaultProducer defaultProducer;

    @Autowired
    private OrderAfterSaleService orderAfterSaleService;

    @Autowired
    private AfterSaleItemDAO afterSaleItemDAO;

    @Autowired
    private OrderAmountDAO orderAmountDAO;

    @Autowired
    private AfterSaleOperateLogFactory afterSaleOperateLogFactory;


    @Override
    public JsonResult<Boolean> cancelOrder(CancelOrderRequest cancelOrderRequest) {
        return null;
    }

    @Override
    public JsonResult<LackDTO> lockItem(LackRequest request) {

        return null;
    }

    @Override
    public JsonResult<Boolean> refundCallback(RefundCallbackRequest payRefundCallbackRequest) {
        String orderId = payRefundCallbackRequest.getOrderId();
        log.info("接收到取消订单支付退款回调,orderId:{}", orderId);
        return orderAfterSaleService.receivePaymentRefundCallback(payRefundCallbackRequest);
    }

    @Override
    public JsonResult<Boolean> receiveCustomerAuditResult(CustomerReviewReturnGoodsRequest customerReviewReturnGoodsRequest) {
        CustomerAuditAssembleRequest customerAuditAssembleRequest=new CustomerAuditAssembleRequest();
        Long afterSaleId = customerReviewReturnGoodsRequest.getAfterSaleId();
        customerAuditAssembleRequest.setAfterSaleId(afterSaleId);
        customerAuditAssembleRequest.setAfterSaleRefundId(customerReviewReturnGoodsRequest.getAfterSaleRefundId());

        Integer auditResult = customerReviewReturnGoodsRequest.getAuditResult();
        customerAuditAssembleRequest.setReviewTime(new Date());
        customerAuditAssembleRequest.setReviewSource(CustomerAuditSourceEnum.SELF_MALL.getCode());
        customerAuditAssembleRequest.setReviewReasonCode(auditResult);
        customerAuditAssembleRequest.setAuditResultDesc(customerReviewReturnGoodsRequest.getAuditResultDesc());
        AfterSaleInfoDO afterSaleInfoDO=afterSaleInfoDAO.getOneByAfterSaleId(afterSaleId);
        //  幂等校验：防止客服重复审核订单
        if (afterSaleInfoDO.getAfterSaleStatus()> AfterSaleStatusEnum.COMMITED.getCode()){
            throw new OrderBizException(OrderErrorCodeEnum.CUSTOMER_AUDIT_CANNOT_REPEAT);
        }

        if (CustomerAuditResult.ACCEPT.getCode().equals(auditResult)){
            //  客服审核通过
            //  参数验证
            String orderId=customerReviewReturnGoodsRequest.getOrderId();
            AfterSaleItemDO afterSaleItemDO = afterSaleItemDAO.getOrderIdAndAfterSaleId(orderId, afterSaleId);
            if (afterSaleItemDO==null){
                throw new OrderBizException(OrderErrorCodeEnum.AFTER_SALE_ITEM_CANNOT_NULL);
            }
            //  更新售后信息
            customerAuditAssembleRequest.setReviewReason(CustomerAuditResult.ACCEPT.getMsg());
            afterSaleInfoDAO.updateCustomerAuditAfterSaleResult(AfterSaleStatusEnum.REVIEW_PASS.getCode(), customerAuditAssembleRequest);

            AfterSaleLogDO afterSaleLogDO=afterSaleOperateLogFactory.get(afterSaleInfoDO, AfterSaleStatusChangeEnum.AFTER_SALE_CUSTOMER_AUDIT_PASS);
            afterSaleLogDAO.save(afterSaleLogDO);
            //执行退款
            ActualRefundMessage message=new ActualRefundMessage();
            message.setOrderId(orderId);
            message.setAfterSaleRefundId(afterSaleId);
            message.setAfterSaleRefundId(customerAuditAssembleRequest.getAfterSaleRefundId());
            message.setLastReturnGoods(customerAuditAssembleRequest.isLastReturnGoods());
            defaultProducer.sendMessage(RocketMqConstant.ACTUAL_REFUND_TOPIC, JSONObject.toJSONString(message), "实际退款");
        }else if (CustomerAuditResult.REJECT.getCode().equals(auditResult)){
            customerAuditAssembleRequest.setReviewReason(CustomerAuditResult.REJECT.getMsg());
            //  审核拒绝更新售后信息
            afterSaleInfoDAO.updateCustomerAuditAfterSaleResult(AfterSaleStatusEnum.REVIEW_REJECTED.getCode(), customerAuditAssembleRequest);
            AfterSaleLogDO afterSaleLogDO = afterSaleOperateLogFactory.get(afterSaleInfoDO, AfterSaleStatusChangeEnum.AFTER_SALE_CUSTOMER_AUDIT_REJECT);
            afterSaleLogDAO.save(afterSaleLogDO);

        }
        return JsonResult.buildSuccess(true);
    }

    @Override
    public JsonResult<Boolean> revokeAfterSale(RevokeAfterSaleRequest request) {
        return null;
    }
}
